
//防抖
let debTime = {
  lasttime1: '',
  timer1: ''
};
let activeIndex = 0; // 当前显示的图片下标
let visible = false; // 是否需要显示工具
let unit = 0.25; // 单次缩放比例
const maxPower = 1 + 15 * unit; // 最大倍率
const minPower = 1 - 2 * unit; // 最小倍率
let power = 1; // 当前放大倍率
let drag = false; // 是否可以拖拽
let dragY = false; // Y轴是否可以拖拽
let dragX = false; // X轴是否可以拖拽
function debounce(fn, wait, num) {
  let now = +new Date();
  if (debTime['lastTime' + num] - now < wait) {
    clearTimeout(debTime['timer' + num]);
  }
  debTime['timer' + num] = setTimeout(() => {
    fn();
    debTime['lastTime' + num] = +new Date();
  }, wait);
}

// 初始化图片预览
export function initImage() {
  const dom = document.createElement('div');
  dom.id = 'ui-image-preview';
  dom.innerHTML = `<div class="ui-image-preview-bg" id="ui-image-preview-bg"></div>
    <span class="ui-image-preview-close"><i class="iconfont icon-guanbi"></i></span>
    <span class="ui-image-preview-left"><i class="iconfont icon-zuobian"></i></span>
    <span class="ui-image-preview-right"><i class="iconfont icon-youbian"></i></span>
    <div class="ui-image-preview-tool-bg">
        <div class="ui-image-preview-tool" id="ui-image-preview-tool">
            <span class="ui-image-preview-reduce"><i class="iconfont icon-suoxiao"></i></span>
            <span class="ui-image-preview-amplify"><i class="iconfont icon-fangda"></i></span>
            <span class="ui-image-preview-reset ui-image-preview-disabled"><i class="iconfont icon-liulan"></i></span>
            <span class="ui-image-preview-down"><i class="iconfont icon-xiazai"></i></span>
        </div>
    </div>
    `;
  document.body.appendChild(dom);
  //
  let domClose, domLeft, domRight, domToolBg;
  for (let i = 0; i < dom.children.length; i++) {
    switch (dom.children[i].className) {
      case 'ui-image-preview-close':
        domClose = dom.children[i];
        break;
      case 'ui-image-preview-left':
        domLeft = dom.children[i];
        break;
      case 'ui-image-preview-right':
        domRight = dom.children[i];
        break;
      case 'ui-image-preview-tool-bg':
        domToolBg = dom.children[i];
        break;
    }
  }
  let domReduce, domAmplify, domReduction, domDown;
  const domToolC = domToolBg.children[0].children;
  for (let i = 0; i < domToolC.length; i++) {
    if (domToolC[i].className.includes('ui-image-preview-reduce')) {
      domReduce = domToolC[i];
    } else if (domToolC[i].className.includes('ui-image-preview-amplify')) {
      domAmplify = domToolC[i];
    } else if (domToolC[i].className.includes('ui-image-preview-reset')) {
      domReduction = domToolC[i];
    } else if (domToolC[i].className.includes('ui-image-preview-down')) {
      domDown = domToolC[i];
    }
  }
  // 对dom绑定事件
  // bind-关闭
  domClose.onclick = () => {
    document.getElementById('ui-image-preview').style.display = 'none';
    window.removeEventListener('wheel', imgWhell);
  };
  // bind-left
  domLeft.onclick = () => {};
  // bind-right
  domRight.onclick = () => {};
  // 工具显示
  domToolBg.onmouseenter = () => {
    domToolBg.children[0].style.cssText = 'transform: translateY(0);';
    visible = true;
  };
  // 工具隐藏
  domToolBg.onmouseleave = () => {
    visible = false;
    debounce(hideFn.bind(this), 5000, 1);
  };
  // 缩小
  domReduce.onclick = reduceFn;
  // 放大
  domAmplify.onclick = amplifyFn;
  // 还原
  domReduction.onclick = function (e) {
    if (e.currentTarget.className.includes('ui-image-preview-disabled')) return;
    power = 1;
    btnStatusFn('ui-image-preview-amplify', false);
    btnStatusFn('ui-image-preview-reduce', false);
    btnStatusFn('ui-image-preview-reset', true);
    const domImage = document.getElementById('ui-image-preview').children[0].children[0];
    domImage.style.cssText = 'margin-left:0;margin-top:0;transform:scale(1);';
  };
  // 下载图片
  domDown.onclick = downImg;
}
// 打开图片预览
export function openImage(list) {
  document.getElementById('ui-image-preview').style.display = 'block';
  resetStatusFn();
  window.removeEventListener('wheel', imgWhell);
  const domImgBg = document.getElementById('ui-image-preview').children[0];
  domImgBg.innerHTML = '';
  const img = document.createElement('img');
  img.src = list[activeIndex];
  img.style.cssText = 'margin-left:0;margin-top:0;transform: scale(1);';
  domImgBg.appendChild(img);
  bindImage();
  setTimeout(() => {
    hideFn();
  }, 5000);
  window.addEventListener('wheel', imgWhell);
}
// 图片滚轮事件
function imgWhell(e) {
  if (e.deltaY < 0) amplifyFn();
  else reduceFn();
}
// 工具栏隐藏
function hideFn() {
  if (visible) return;
  const domTool = document.getElementById('ui-image-preview-tool');
  domTool.style.cssText = 'transform: translateY(100%);';
}
/******* 
 * @Author: 刘强
 * @description: 
 * @return {*}
 */
// 图片缩小
function reduceFn() {
  btnStatusFn('ui-image-preview-amplify', false);
  if (power > minPower) power = power - unit;
  scaleFn();
  btnStatusFn('ui-image-preview-reset', power === 1);
  checkImage();
  if (power <= minPower) {
    btnStatusFn('ui-image-preview-reduce', true);
    return;
  }
}
// 图片放大
function amplifyFn() {
  btnStatusFn('ui-image-preview-reduce', false);
  if (power < maxPower) power = power + unit;
  scaleFn();
  btnStatusFn('ui-image-preview-reset', power === 1);
  checkImage();
  if (power >= maxPower) {
    btnStatusFn('ui-image-preview-amplify', true);
    return;
  }
}
// 判断图片是否超屏
function checkImage() {
  const domImg = document.getElementById('ui-image-preview-bg').children[0];
  const { height, width } = domImg.getBoundingClientRect();
  const maxHeight = window.innerHeight;
  const maxWidth = window.innerWidth;
  dragY = height > maxHeight;
  dragX = width > maxWidth;
  domImg.style.marginLeft = `0`;
  domImg.style.marginTop = `0`;
}
// 图片缩放
function scaleFn() {
  const domImage = document.getElementById('ui-image-preview').children[0].children[0];
  const old = domImage.style.cssText;
  domImage.style.cssText = `${old}transform: scale(${power});`;
}
// 图片拖拽
function dragImageFn(e) {
  if (!drag) return;
  const { movementX, movementY } = e;
  const domImg = document.getElementById('ui-image-preview-bg').children[0];
  const { height, width } = domImg.getClientRects()[0];
  let left = parseInt(domImg.style.marginLeft) + movementX;
  let top = parseInt(domImg.style.marginTop) + movementY;
  // 左右边距控制
  if (left + width <= window.innerWidth) {
    left = -(width - window.innerWidth);
  }
  if (width - left <= window.innerWidth) {
    left = width - window.innerWidth;
  }
  // 上下边距空置
  if (height - top <= window.innerHeight) {
    top = height - window.innerHeight;
  }
  if (height + top <= window.innerHeight) {
    top = -(height - window.innerHeight);
  }
  if (dragX) domImg.style.marginLeft = `${left}px`;
  if (dragY) domImg.style.marginTop = `${top}px`;
}
// 图片事件绑定
function bindImage() {
  const domImage = document.getElementById('ui-image-preview').children[0].children[0];
  domImage.onmousedown = () => {
    drag = true;
  };
  window.addEventListener('mouseup', () => {
    drag = false;
  });
  window.addEventListener('mousemove', dragImageFn);
}
// 图片下载
function downImg() {
  var xmr = new XMLHttpRequest();
  xmr.open('GET', 'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg', true);
  xmr.responseType = 'blob';
  xmr.onload = function (e) {
    var url = window.URL.createObjectURL(xmr.response);
    var a = document.createElement('a');
    a.href = url;
    a.download = '';
    a.click();
  };
  xmr.send();
}
// 按钮状态变化
function btnStatusFn(name, disabled) {
  const list = document.getElementById('ui-image-preview-tool').children;
  let domTarget;
  for (let i = 0; i < list.length; i++) {
    if (list[i].className.includes(name)) {
      domTarget = list[i];
      break;
    }
  }
  if (disabled) {
    domTarget.classList.add('ui-image-preview-disabled');
  } else {
    domTarget.classList.remove('ui-image-preview-disabled');
  }
}
// 状态初始化
function resetStatusFn() {
  activeIndex = 0; // 当前显示的图片下标
  visible = false; // 是否需要显示工具
  unit = 0.25; // 单次缩放比例
  power = 1; // 当前放大倍率
  drag = false; // 是否可以拖拽
  document.getElementById('ui-image-preview-tool').style.transform = 'translateY(0)';
}
